﻿namespace ElencySolutions.ImageMap.Properties
{
    using System.IO;
    using System.Reflection;
    using System.Xml;
    using EPiServer.Core;

    /// <summary>
    /// Language helper class
    /// </summary>
    public static class LanguageHelper
    {
        private static XmlDocument _document;

        /// <summary>
        /// Tries to get text from a language file based on the supplied xpath expression.  If the text
        /// cannot be found a fallback value is retrieved from an embedded resource
        /// </summary>
        /// <param name="xpath"></param>
        /// <returns></returns>
        public static string Translate(string xpath)
        {
            return LanguageManager.Instance.TranslateFallback(xpath, GetFallbackText(xpath));
        }

        /// <summary>
        /// Gets the fall back text from the embedded resource
        /// </summary>
        /// <param name="xpath"></param>
        /// <returns></returns>
        private static string GetFallbackText(string xpath)
        {
            if (_document == null)
            {
                string xml = string.Empty;

                using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ElencySolutions.ImageMap.Properties.lang.lang_EN.xml"))
                {
                    using (StreamReader streamReader = new StreamReader(stream))
                    {
                        xml = streamReader.ReadToEnd();
                    }
                }

                _document = new XmlDocument();
                _document.LoadXml(xml);
            }

            if (!xpath.StartsWith("/"))
                xpath = string.Concat("/", xpath);

            return _document.SelectSingleNode("/languages/language" + xpath).InnerText.Trim();
        }
    }
}
